<template>
  <div>
    <div class="map-home" id="map-home">
      <div id="map"></div>
    </div>
    <div :class="showLeft ? 'left-info' : 'left-hide'">
      <visit-chart ref="visitChart"/>
      <user-chart ref="userChart" class="mb20"/>
    </div>
    <div :class="showRight ? 'right-info' : 'right-hide'">
      <base-info ref="baseInfo"/>
    </div>
  </div>
</template>

<script>
  import {deepClone} from "@/utils";
  import baseInfo from './components/baseInfo';
  import visitChart from './components/visitChart';
  import _ from 'lodash'
  import userChart from './components/userChart';
  import screenfull from 'screenfull'
  import {_createControlBar, _createArea, _openFullscreen, _exitFullScreen} from "./util/control.js";
  import {_createLoca, _createLocaPolygon} from "./util/loca.js";
  import {carListApi, siteListApi, workListApi, workSaveApi} from '@/api/dashboard';
  import {
    _createRoadLine,
    _createDiyLine,
    _createInPointTrigger,
    _createOutPointTrigger,
    _createInLine,
    _createOutLine
  } from "./util/roadLine.js";

  export default {
    name: 'DataV',
    components: {baseInfo, visitChart, userChart},
    data() {
      return {
        map: '',
        loca: '',
        showLeft: true,
        showRight: true,
        tok: '25.c1b874a69b7ee3c3b67f938dd174d85d.315360000.1940137714.282335-19911549',
        markerList: [],
        freeCarList: [],
        workCarList: [],
        siteFlag: true,
        touchFlag:true,
        touchNum:0,
      }
    },
    mounted() {

      this.isMobile()
      this.mapInit();
      this.handleSpaek("你好,欢迎进入零碳未来!")
      let workTimer = setInterval(this.handleWork, 30000)
      let touchTimer = setInterval(this.handleTouch, 1000)
      this.$once('hook:beforeDestroy', () => {
        clearInterval(workTimer);
        clearInterval(touchTimer);
      })

    },
    methods: {
      //语音播报
      handleSpaek(str) {
        new Audio('https://tts.baidu.com/text2audio?cuid=19911549&lan=zh&ctp=1&tok=25.c1b874a69b7ee3c3b67f938dd174d85d.315360000.1940137714.282335-19911549&tex=' + str).play();
      },
      isMobile() {
        this.flag = navigator.userAgent.match(
          /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
        );
        console.log(this.flag);
        if (this.flag === null) {
          console.log("pc端");

        } else {
          console.log("移动端");
          this.showLeft = false
          this.showRight = false
        }
      },
      handleTouch(){
        if(!this.touchFlag){
          if(this.touchNum > 10){
            this.touchFlag =true;
          }else{
            this.touchNum+=1
          }
        }
      },
      touchFun(){
        this.touchFlag =false;
        this.touchNum =0;
        this.showLeft = false;
        this.showRight = false;
      },
      handleWork() {
        let that = this;

        let param = {
          'car_id': that.freeCarList[0].id,
          'lat': 1,
          'lng': 2,
          'supply_type': '1',
          'supply_num': 100,
          'order_id': 111,
          'work_time': 1,
          'site_id': Math.random() * 8 + 1,
          'status': 1,
          'collect_lat': 1,
          'collect_lng': 2
        }
        console.log('任务参数', param)
        workSaveApi(param).then(async res => {
          console.log(res)

          that.markerLineInit()
        })

      },
      markerLineInit() {
        let that = this;
        // 创建一个车辆Icon
        let carIcon = new AMap.Icon({
          // 图标尺寸
          size: new AMap.Size(18, 36),
          // 图标的取图地址
          image: 'https://webapi.amap.com/ui/1.1/ui/misc/PathSimplifier/examples/imgs/car.png',
          // 图标所用图片大小
          imageSize: new AMap.Size(18, 36),
          // 图标取图偏移量
          imageOffset: new AMap.Pixel(0, 0)
        })

        //创建需热供热动画
        workListApi().then(async res => {
          console.log('供热路线', res)
          that.map.remove(that.workCarList)

          that.workCarList = []

          let dataIn = {
            "type": "FeatureCollection",
            "features": []
          }

          let dataOut = {
            "type": "FeatureCollection",
            "features": []
          }

          for (let key in res) {
            if (res[key].supply_type == '2') {
              dataIn['features'].push({
                "type": "Feature",
                "properties": {
                  "type": 0,
                  "ratio": 0.0577,
                  "lineWidthRatio": 1
                },
                "geometry": {
                  "type": "LineString",
                  "coordinates": [
                    [
                      res[key].car_lat, res[key].car_lng
                    ],
                    [
                      res[key].site_lat, res[key].site_lng
                    ]
                  ]
                }
              })
            } else {
              dataOut['features'].push({
                "type": "Feature",
                "properties": {
                  "type": 0,
                  "ratio": 0.0577,
                  "lineWidthRatio": 1
                },
                "geometry": {
                  "type": "LineString",
                  "coordinates": [
                    [
                      res[key].car_lat, res[key].car_lng
                    ],
                    [
                      res[key].site_lat, res[key].site_lng
                    ]
                  ]
                }
              })
            }
            // let carMarker = new AMap.Marker({
            //   position: new AMap.LngLat(res[key].car_lat, res[key].car_lng),
            //   icon: carIcon,
            //   offset: new AMap.Pixel(0, 0)
            // });
            // carMarker.moveTo([res[key].site_lat, res[key].site_lng],12000)
            let animationMarker = new AMap.Marker({
              position: new AMap.LngLat(res[key].car_lat, res[key].car_lng),
              icon: carIcon,
              offset: new AMap.Pixel(-8, 0)
            });
            animationMarker.setLabel({
              offset: new AMap.Pixel(0, 0),  //设置文本标注偏移量
              content: "<div>"+res[key].supply_num+"kj</div>", //设置文本标注内容
              direction: 'top' //设置文本标注方位
            });
            animationMarker.on('click', function () {
              animationMarker.setTop(true,99999999)
              that.touchFun()
              // that.loca.viewControl.addAnimates([{
              //   rotation: {
              //     value: 360 - animationMarker.lastAngle > 180 ? - animationMarker.lastAngle : 360 - animationMarker.lastAngle ,
              //     control: [[0, 0], [0, 0]],
              //     timing: [0.1,0.1,0.1,0.1],
              //     duration: 500,
              //   },
              // }], function () {})
              animationMarker.setLabel({
                offset: new AMap.Pixel(0, 0),  //设置文本标注偏移量
                content: "<div class = 'label-marker-diy'><p class='p1'>详细信息</p><p>车辆名称:111</p><p>司机名称:1111</p><p>车牌号:11111</p><p>状态:正在前往执行任务</p></div>", //设置文本标注内容
                direction: 'top' //设置文本标注方位
              });
              setTimeout(function () {
                animationMarker.setTop(false)
                animationMarker.setLabel({
                  offset: new AMap.Pixel(0, 0),  //设置文本标注偏移量
                  content: "<div>"+res[key].supply_num+"kj</div>", //设置文本标注内容
                  direction: 'top' //设置文本标注方位
                });
              },10000);
            });

            setTimeout(function () {
              animationMarker.moveTo([res[key].site_lat, res[key].site_lng], {
                duration: res[key].work_time*60*1000,
                delay: 500,
              })
            }, 1000);
            that.workCarList.push(animationMarker)
            if (key == res.length - 1) {
              that.handleSpaek(res[key].site_name+"触发阈值45°,预计需要配送100000焦耳热量,正在检查库存...")
              if(that.touchFlag){
                setTimeout(function () {
                  that.animate([res[key].car_lat, res[key].car_lng],[res[key].site_lat, res[key].site_lng])
                }, 1000)
              }


              setTimeout(function () {
                that.handleSpaek("正在调度车辆...")
              }, 8000)
              setTimeout(function () {

                that.handleSpaek("正在出单...")
              }, 10000)
              setTimeout(function () {
                that.handleSpaek("记账完成,已规划最优路线..."+res[key].car_name+"已出发,预计"+((new Date().getHours())+1)+":00到达,作业时长30分钟")
              }, 12000)

            }
          }
          if (dataIn['features'].length > 0) {
            //创建供热动画路线
            _createInLine(dataIn, that.loca, that.map)
          }
          if (dataOut['features'].length > 0) {
            //创建需热动画路线
            _createOutLine(dataOut, that.loca, that.map)
          }
          console.log('任务车辆', that.workCarList)
          that.map.add(that.workCarList)

        })
        carListApi().then(async res => {
          console.log('车辆', res)
          that.map.remove(that.markerList)
          this.markerList = []
          that.freeCarList = []
          for (let key in res) {
            if (res[key].status == '2') {
              that.freeCarList.push(res[key])
              // 将 icon 传入 marker
              let carMarker = new AMap.Marker({
                position: new AMap.LngLat(res[key].lat, res[key].lng),
                icon: carIcon,
                offset: new AMap.Pixel(-8, 0)
              });
              carMarker.setLabel({
                offset: new AMap.Pixel(0, 0),  //设置文本标注偏移量
                content: "<div>"+res[key].temperature.split(',')[0]+"℃,"+res[key].temperature.split(',')[1]+"℃</div><div>"+res[key].temperature.split(',')[2]+"℃,"+res[key].temperature.split(',')[3]+"℃</div><div>"+res[key].temperature.split(',')[4]+"℃,"+res[key].temperature.split(',')[5]+"℃</div>", //设置文本标注内容
                direction: 'top' //设置文本标注方位
              });
              carMarker.on('click', function () {
                carMarker.setTop(true,99999999)
                that.touchFun()
                carMarker.setLabel({
                  offset: new AMap.Pixel(0, 0),  //设置文本标注偏移量
                  content: "<div class = 'label-marker-diy'><p class='p1'>详细信息</p><p>车辆名称: "+res[key].name+"</p><p>司机名称: "+res[key].driver_name+"</p><p>车牌号: "+res[key].car_number+"</p><p>温控(℃): "+res[key].temperature+"</p><p>状态: 待机中</p></div>", //设置文本标注内容
                  direction: 'top' //设置文本标注方位
                });
                setTimeout(function () {
                  carMarker.setLabel({
                    offset: new AMap.Pixel(0, 0),  //设置文本标注偏移量
                    content: "<div>"+res[key].temperature.split(',')[0]+"℃,"+res[key].temperature.split(',')[1]+"℃</div><div>"+res[key].temperature.split(',')[2]+"℃,"+res[key].temperature.split(',')[3]+"℃</div><div>"+res[key].temperature.split(',')[4]+"℃,"+res[key].temperature.split(',')[5]+"℃</div>", //设置文本标注内容
                    direction: 'top' //设置文本标注方位
                  });
                },10000)
                carMarker.setTop(false)
              });
              that.markerList.push(carMarker)
            }
          }
          console.log('freeCar', that.freeCarList)
          that.map.add(that.markerList)
        })
      },
      // 初始加载底图
      mapInit() {
        let that = this;
        that.map = new AMap.Map("map", {
          center: [106.56288, 29.556742], // [107.755852, 29.590834],
          resizeEnable: true,
          expandZoomRange: true,
          zooms: [3, 20],
          zoom: 10.5, //8.35,
          showBuildingBlock: true,
          showLabel: true,
          pitch: 35, // 地图俯仰角度，有效范围 0 度- 83 度
          viewMode: '3D', // 地图模式
          mapStyle: "amap://styles/e5420c85956f841f8298d24762bfa5e3", // "amap://styles/f2a14a729d5018cebe9aa5a844e8c053" "amap://styles/cf4bbeff185671422895aaff7434766a"
        });


        //3D罗盘
        _createControlBar(that.map)

        //绘制行政区域
        _createArea(that.map, "重庆")

        //添加自由动画视角
        that.loca = _createLoca(that.map)

        //绘制3D建筑
        // _createLocaPolygon(that.loca)


        //暂时不适用 会飘移
        //_createDiyLine(that.map)
        let siteIcon = new AMap.Icon({
          // 图标尺寸
          size: new AMap.Size(10, 10),
          // 图标的取图地址
          image: ' https://a.amap.com/Loca/static/loca-v2/demos/images/blue.png',
          // 图标所用图片大小
          imageSize: new AMap.Size(10, 10),
          // 图标取图偏移量
          imageOffset: new AMap.Pixel(0, 0)
        })
        //渲染站点
        siteListApi().then(async res => {
          console.log('站点', res)
          let dataIn = {
            "type": "FeatureCollection",
            "features": []
          }
          let dataOut = {
            "type": "FeatureCollection",
            "features": []
          }
          for (let key in res) {
            if (res[key].type == 2) {
              dataIn['features'].push({
                "type": "Feature",
                "geometry": {
                  "type": "Point",
                  "coordinates": [res[key].lat, res[key].lng]
                }
              })
            } else {
              dataOut['features'].push({
                "type": "Feature",
                "geometry": {
                  "type": "Point",
                  "coordinates": [res[key].lat, res[key].lng]
                }
              })
            }
            let siteMarker = new AMap.Marker({
              position: new AMap.LngLat(res[key].lat, res[key].lng),
              icon: siteIcon,
              offset: new AMap.Pixel(-5, -5)
            });
            siteMarker.on('click', function () {
              that.touchFun()
              siteMarker.setTop(true,99999999)
              siteMarker.setLabel({
                offset: new AMap.Pixel(0, 0),  //设置文本标注偏移量
                content: "<div class = 'label-marker-diy'><p class='p1'>详细信息</p><p>站点名称: "+res[key].name+"</p><p>站点位置: "+res[key].address+"</p><p>站点类型: "+ (res[key].type == '1' ? '供热' : '需热') +"</p><p>状态: 正常</p></div>", //设置文本标注内容
                direction: 'top' //设置文本标注方位
              });
              setTimeout(function () {
                siteMarker.setLabel({
                  offset: new AMap.Pixel(0, 0),  //设置文本标注偏移量
                  content: "<div></div>", //设置文本标注内容
                  direction: 'top' //设置文本标注方位
                });
                siteMarker.setTop(false)
              },10000);
            });
            that.map.add(siteMarker)
          }

          //创建需热呼吸点
          _createOutPointTrigger(dataIn, that.loca, that.map)
          //创建供热呼吸点
          _createInPointTrigger(dataOut, that.loca, that.map)
        })
        that.markerLineInit()
        that.map.on("click",function () {
          that.touchFun()
        })
        that.map.on('complete', function () {
          that.loca.animate.start();
          //创建行驶路线图
          //_createRoadLine(that.map)
          // document.querySelector('.start-btn').addEventListener('click', function () {});
          // setTimeout(animate, 2000);
          screenfull.toggle()
          document.addEventListener('keyup', function (e) {
            if (e.keyCode == 27) {
              location.href='/'
            }
          })
        });

      },
      animate(startPoint,endPoint) {
        let that =this

        if(that.showLeft){
          that.showLeft = false;

        }
        if(that.showRight){
          that.showRight = false;

        }
        let speed = 1;
        // 镜头动画
        that.map.setZoom(10.5, true);
        that.map.setPitch(0, true);
        that.map.setCenter(startPoint, true);
        that.map.setRotation(1, true);
        //pl.hide(1000);

        // 下钻
        that.loca.viewControl.addAnimates([{
          pitch: {
            value: 0,
            control: [[0, 20], [1, 0]],
            timing: [0, 0, 0.8, 1],
            duration: 3000 / speed,
          },
          zoom: {
            value: 12.5,
            control: [[0, 12.8], [1, 15.9]],
            timing: [0, 0, 0.8, 1],
            duration: 3000 / speed,
          },
          rotation: {
            value: -20,
            control: [[0, 20], [1, -20]],
            timing: [0, 0, 0.8, 1],
            duration: 2000 / speed,
          },
        }], function () {

          that.loca.viewControl.addAnimates([
            // 寻迹
            {
              center: {
                value: startPoint,
                control: [startPoint, endPoint],
                timing: [0.3, 0, 0.1, 1],
                duration: 8000 / speed,
              },
              zoom: {
                value: 12.5,
                control: [[0.3, 15], [1, 17]],
                timing: [0.3, 0, 0.7, 1],
                duration: 4000 / speed,
              },
              pitch: {
                value: 50,
                control: [[0.3, 0], [1, 50]],
                timing: [0.3, 0, 1, 1],
                duration: 3000 / speed,
              },
              rotation: {
                value: -80,
                control: [[0, -20], [1, -80]],
                timing: [0, 0, 1, 1],
                duration: 1000 / speed,
              },
            },
            // {
            //   // 环绕
            //   pitch: {
            //     value: 50,
            //     control: [[0, 40], [1, 50]],
            //     timing: [0.3, 0, 1, 1],
            //     duration: 7000 / speed,
            //   },
            //   rotation: {
            //     value: 260,
            //     control: [[0, -80], [1, 260]],
            //     timing: [0, 0, 0.7, 1],
            //     duration: 7000 / speed,
            //   },
            //   zoom: {
            //     value: 15,
            //     control: [[0.3, 16], [1, 17]],
            //     timing: [0.3, 0, 0.9, 1],
            //     duration: 5000 / speed,
            //   },
            // },
            {
              // 拉起
              center: {
                value: startPoint,
                control: [startPoint, endPoint],
                timing: [0.3, 0, 0.7, 1],
                duration: 2000 / speed,
              },
              pitch: {
                value: 30,
                control: [[0, 0], [1, 100]],
                timing: [0.1, 0, 0.7, 1],
                duration: 2000 / speed,
              },
              rotation: {
                value: 361,
                control: [[0, 260], [1, 361]],
                timing: [0.3, 0, 0.7, 1],
                duration: 2000 / speed,
              },
              zoom: {
                value: 10.8,
                control: [[0, 17.5], [1, 13.8]],
                timing: [0.3, 0, 0.7, 1],
                duration: 2500 / speed,
              },
            }], function () {
            //pl.hide(1000);
            //setTimeout(animate, 2000);
            console.log('结束');

            that.showLeft = true;
            that.showRight = true;

          });
        });
      }
    }

  }
</script>

<style lang="scss" scoped>
  .map-home {
    #map {
      width: 100vw;
      height: 100vh;
    }
  }

  .left-info {
    width: 25vw;
    height: 90vh;
    position: absolute;
    top: 3vh;
    left: 1vw;
  }

  .left-hide{
    display: none;
  }

  .right-info {
    width: 25vw;
    height: 90vh;
    position: absolute;
    top: 8vh;
    right: 1vw;
  }

  .right-hide{
    display: none;
  }

</style>
<style>

  .amap-controlbar {
    z-index: 1 !important;
  }

  .amap-marker-label{
    position: absolute;
    z-index: 2;
    border: 0 !important;
    background-color:rgba(255,255,255,0) !important;
    color: #fff !important;
    font-weight: bold;
    white-space: nowrap;
    cursor: default;
    padding: 3px;
    font-size: 12px;
    line-height: 14px;
    z-index: 999;
  }
  .label-marker-diy{
    background: #fff;
    color: #000;
    padding: 20px 15px 10px 15px;
    animation: contentSlipToBottom 1s;
    color: #222;
    font-weight: bold;
  }
  .label-marker-diy p{
    margin-bottom: 5px;
  }
  .label-marker-diy .p1{
    padding-bottom:3px ;
    margin: -10px 0 10px 0;
    border-bottom:1px solid #ccc;
  }
  @keyframes contentSlipToBottom {
    0% {
      transform:rotateX(90deg);
    }
    100% {
      transform:rotateX(0deg);
    }
  }
</style>
